package com.example.houtai.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.digest.MD5;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.houtai.entity.SysUser;
import com.example.houtai.entity.TbSmsRecords;
import com.example.houtai.service.ISysUserService;
import com.example.houtai.service.ITbSmsRecordsService;
import com.org.vo.ResultEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 登陆 注册 短信验证码
 * @author 王国庆
 */
@Slf4j
@RestController
@RequestMapping("/sys/sys-login")
public class LoginController {


    /**
     * appId   请联系销售，或者在页面中 获取
     */
    @Value("${SMS.appId}")
    String appId;

    // 密钥 请联系销售，或者在页面中 获取
    @Value("${SMS.secretKey}")
    String secretKey;

    // 接口地址 请联系销售获取
    @Value("${SMS.host}")
    String host;

    // 加密算法
    @Value("${SMS.algorithm}")
    String algorithm;

    // 编码
    String encode = "UTF-8";

    // 是否压缩
    boolean isGizp = true;

    @Autowired
    private ITbSmsRecordsService smsRecordsService;

    @Autowired
    private ISysUserService sysUserService;


    @Resource
    PasswordEncoder passwordEncoder;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 获取短信验证码  亿美API接口
     * @param smsRecords
     * @return
     */
    @RequestMapping("/getCode")
    public ResultEntity getCode(TbSmsRecords smsRecords) {
        /*QueryWrapper<TbSmsRecords> wrapper = new QueryWrapper<>();
        wrapper.eq("mobile", smsRecords.getMobile());
        List<TbSmsRecords> list = smsRecordsService.list(wrapper);
        if (list.size() > 0) {
            TbSmsRecords records = list.get(list.size() - 1);
            Date nowDate = new Date();
            if ((nowDate.getTime() - records.getCreateTime().getTime()) / 1000 < 120) {
                return ResultEntity.error("请勿2分钟内重复发送短信", false);
            }
        }*/
        String mobile = smsRecords.getMobile();
        QueryWrapper<SysUser> sysUserQueryWrapper = new QueryWrapper<>();
        sysUserQueryWrapper.eq("mobile", mobile);
        SysUser userServiceOne = sysUserService.getOne(sysUserQueryWrapper);
        if (!BeanUtil.isEmpty(userServiceOne)){
            return ResultEntity.error("该手机号已经注册，请换个手机号", false);
        }

        if (redisTemplate.hasKey(mobile)){
            return ResultEntity.error("请勿重复发送短信", false);
        }
        /*StringBuffer sb = new StringBuffer();
        for (int i = 0; i < 6; i++) {
            sb.append((int) (Math.random() * 10));
        }*/
        /// 获取随机6位 数字验证码
        String phoneCode = RandomUtil.randomNumbers(6);
        log.info("验证码：" + phoneCode);

        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String timestamp = simpleDateFormat.format(date);
        String content = "【维数公寓】您的短信验证码为 " + phoneCode + "，" +" 2分钟内有效，请勿告知他人。";
        String sign = MD5.create().digestHex(appId + secretKey + timestamp);
        HashMap<String, Object> hashMap = new HashMap<>(5);
        hashMap.put("appId",appId);
        hashMap.put("timestamp",timestamp);
        hashMap.put("sign",sign);
        hashMap.put("mobiles",mobile);
        hashMap.put("content",content);
        log.info("短信验证：{}"+content);
        String post = HttpUtil.post(host, hashMap);
        log.info("短信验证回调返回值：{}"+post);
        JSONObject jsonObject = JSONObject.parseObject(post);
        String code = (String) jsonObject.get("code");
        redisTemplate.opsForValue().setIfAbsent(mobile, phoneCode, 2, TimeUnit.MINUTES);
        if ("SUCCESS".equals(code)){
            return ResultEntity.ok(true);
        }
        return ResultEntity.error("短信发送失败", false);
//        SMSUtil.smsSend(appId, secretKey, host, algorithm, encode, isGizp, phoneCode, "2", smsRecords.getMobile());
       /* smsRecords.setMobileCode(sb);
        smsRecords.setCreateTime(new Date());
        smsRecords.setParam("{\"code\":\"" + sb + "\"}");
        smsRecords.setStatus("101");
        smsRecordsService.save(smsRecords);*/

    }

    /**
     * 重置密码时获取短信验证码  亿美API接口
     * @param smsRecords
     * @return
     */
    @RequestMapping("/getupdcode")
    public ResultEntity getUpdatePasswordCode(TbSmsRecords smsRecords) {
        String mobile = smsRecords.getMobile();
        if (redisTemplate.hasKey(mobile)){
            return ResultEntity.error("请勿重复发送短信", false);
        }
        /*StringBuffer sb = new StringBuffer();
        for (int i = 0; i < 6; i++) {
            sb.append((int) (Math.random() * 10));
        }*/
        /// 获取随机6位 数字验证码
        String phoneCode = RandomUtil.randomNumbers(6);
        log.info("验证码：" + phoneCode);

        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String timestamp = simpleDateFormat.format(date);
        String content = "【维数公寓】您的短信验证码为 " + phoneCode + "，" +" 2分钟内有效，请勿告知他人。";
        String sign = MD5.create().digestHex(appId + secretKey + timestamp);
        HashMap<String, Object> hashMap = new HashMap<>(5);
        hashMap.put("appId",appId);
        hashMap.put("timestamp",timestamp);
        hashMap.put("sign",sign);
        hashMap.put("mobiles",mobile);
        hashMap.put("content",content);
        log.info("短信验证：{}"+content);
        String post = HttpUtil.post(host, hashMap);
        log.info("短信验证回调返回值：{}"+post);
        JSONObject jsonObject = JSONObject.parseObject(post);
        String code = (String) jsonObject.get("code");
        redisTemplate.opsForValue().setIfAbsent(mobile, phoneCode, 2, TimeUnit.MINUTES);
        if ("SUCCESS".equals(code)){
            return ResultEntity.ok(true);
        }
        return ResultEntity.error("短信发送失败", false);
//        SMSUtil.smsSend(appId, secretKey, host, algorithm, encode, isGizp, phoneCode, "2", smsRecords.getMobile());
       /* smsRecords.setMobileCode(sb);
        smsRecords.setCreateTime(new Date());
        smsRecords.setParam("{\"code\":\"" + sb + "\"}");
        smsRecords.setStatus("101");
        smsRecordsService.save(smsRecords);*/

    }

    @RequestMapping("reg")
    public ResultEntity reg(@RequestBody SysUser sysUser, HttpServletResponse response) {
        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        wrapper.eq("mobile", sysUser.getMobile());
        List<SysUser> list = sysUserService.list(wrapper);
        if (list.size() > 0) {
            return ResultEntity.error("用户已存在!", false);
        }

        if (!redisTemplate.hasKey(sysUser.getMobile())){
            return ResultEntity.error("验证码已过期!!", false);
        }

        String o = (String) redisTemplate.opsForValue().get(sysUser.getMobile());
        if (o.equals(sysUser.getCode())){
            sysUser.setCreateTime(new Date());
            String encode = passwordEncoder.encode(sysUser.getPassword());
            sysUser.setPassword(encode);

            sysUser.setContactMember(sysUser.getUsername());
            sysUser.setUsername(sysUser.getMobile());
            sysUser.setDelFlag(0);
            sysUser.setStatus(1);
            sysUser.setApprovalFlag(4);
            sysUserService.save(sysUser);
            return ResultEntity.ok(sysUser.getUserId());
        }
        return ResultEntity.error("验证码错误!!", false);
        /*QueryWrapper<TbSmsRecords> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("mobile", sysUser.getMobile());
        List<TbSmsRecords> list1 = smsRecordsService.list(wrapper1);
        if (list1.size() > 0) {
            TbSmsRecords records = list1.get(list1.size() - 1);
            Date nowDate = new Date();
            if ((nowDate.getTime() - records.getCreateTime().getTime()) / 1000 > 120) {

            }
            QueryWrapper<TbSmsRecords> wrapper2 = new QueryWrapper<>();
            wrapper2.eq("mobile", sysUser.getMobile());
            wrapper2.eq("mobile_code", sysUser.getCode());
            List<TbSmsRecords> list2 = smsRecordsService.list(wrapper2);
            if (list2.size() < 1) {
                return ResultEntity.error("验证码错误!!", false);
            }
        }*/

    }
}
